package controllers

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	// "fmt"

	model "mars-backend/models"
	"mars-backend/utils"
	"net/http"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"gopkg.in/mgo.v2/bson"
)

type UserController struct {
	beego.Controller
}

var MarsCookies map[string]utils.MarCookies

func (user *UserController) IsLoggined() {
	if !utils.IsLoggedIn(user.Ctx.GetCookie("key"), SavedCookies) {
		user.Ctx.Output.Status = http.StatusUnauthorized
		user.Ctx.Output.Body([]byte(`{"error":"Unauthorized"}`))
		return
	}
}

//AddUser 添加用户
func (user *UserController) AddUser() {
	body := user.Ctx.Input.RequestBody
	// bodyJson := uct.Ctx.Input.RequestBody
	beego.Info("RequestBody")
	beego.Info(string(user.Ctx.Input.RequestBody))
	var c model.User
	err := json.Unmarshal(body, &c)

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	userID := bson.NewObjectId()

	data := []byte(c.Password)
	has := md5.Sum(data)
	passwordmd5 := fmt.Sprintf("%x", has)

	// birthdate, _ := time.Parse("2018-01-01", c.BirthDate)
	uctObj := &model.User{
		ID:         userID,
		Mobile:     c.Mobile,
		Email:      c.Email,
		CreateTime: time.Now(),
		IsDelete:   0,
		Password:   passwordmd5,
	}

	utable := session.DB("").C(UserTable)
	var checkResult model.User
	utable.Find(bson.M{"mobile": c.Mobile, "isdelete": 0}).One(&checkResult)

	if checkResult.ID != "" {
		user.HandleError(fmt.Errorf("该手机号已经被注册"))
	}
	utable.Insert(uctObj)

	resMap := make(map[string]interface{})
	resMap["id"] = userID
	resData, err := json.Marshal(resMap)
	user.HandleError(err)

	user.Ctx.Output.Status = http.StatusOK

	user.Ctx.Output.Body(resData)

}

func (user *UserController) UpdateBasicInfo() {
	body := user.Ctx.Input.RequestBody
	// bodyJson := uct.Ctx.Input.RequestBody
	beego.Info("RequestBody")
	beego.Info(string(user.Ctx.Input.RequestBody))
	var c model.User
	err := json.Unmarshal(body, &c)

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)

	err = utable.Update(bson.M{"_id": c.ID}, bson.M{"$set": bson.M{
		"name":              c.Name,
		"sex":               c.Sex,
		"nation":            c.Nation,
		"originaddress":     c.OriginAddress,
		"birthaddress":      c.BirthAddress,
		"birthdate":         c.BirthDate,
		"mobile":            c.Mobile,
		"email":             c.Email,
		"professionaltitle": c.Professionaltitle,
		"isdelete":          0,
	},
	},
	)

	user.HandleError(err)

	user.Ctx.Output.Status = http.StatusOK

}

func (user *UserController) UpdateEducationInfo() {
	body := user.Ctx.Input.RequestBody

	var c model.User
	err := json.Unmarshal(body, &c)

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)

	err = utable.Update(bson.M{"_id": c.ID}, bson.M{"$set": bson.M{
		"education": c.Education,
		"isdelete":  0,
	},
	},
	)

	user.HandleError(err)

	user.Ctx.Output.Status = http.StatusOK

}
func (user *UserController) UpdateWorkInfo() {
	body := user.Ctx.Input.RequestBody

	var c model.User
	err := json.Unmarshal(body, &c)

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)

	err = utable.Update(bson.M{"_id": c.ID}, bson.M{"$set": bson.M{
		"workexperience": c.WorkExperience,
		"isdelete":       0,
	},
	},
	)

	user.HandleError(err)

	user.Ctx.Output.Status = http.StatusOK

}

func (user *UserController) UpdateOtherInfo() {
	body := user.Ctx.Input.RequestBody

	var c model.User
	err := json.Unmarshal(body, &c)

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)

	err = utable.Update(bson.M{"_id": c.ID}, bson.M{"$set": bson.M{
		"honor":               c.Honor,
		"company":             c.Company,
		"companyyear":         c.CompanyYear,
		"companynature":       c.CompanyNature,
		"companyduty":         c.CompanyDuty,
		"industry":            c.Industry,
		"industrychain":       c.IndustryChain,
		"companycontribution": c.CompanyContribution,
		"advantage":           c.Advantage,
		"requirement":         c.Requirement,
		"supply":              c.Supply,
		"isdelete":            0,
	},
	},
	)

	user.HandleError(err)

	user.Ctx.Output.Status = http.StatusOK

}

func (user *UserController) DelOneUser() {
	var id string
	params := user.Ctx.Input.Params()
	id = params[":id"]
	if id == "" {
		user.Ctx.Output.Status = http.StatusInternalServerError
		user.Ctx.Output.Body([]byte(`{"result":"id is none!"}`))
		return
	}
	utils.DeleteUserById(id)
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body([]byte(`{"result":"delete user successfully!"}`))
}

func (user *UserController) DelMultiUser() {
	var dlist model.DeleteUserList
	json.Unmarshal(user.Ctx.Input.RequestBody, &dlist)

	if len(dlist.Userid) == 0 {
		user.Ctx.Output.Status = http.StatusInternalServerError
		user.Ctx.Output.Body([]byte(`{"result":"id is none!"}`))
		return
	}
	for _, id := range dlist.Userid {
		utils.DeleteUserById(id)
		user.Ctx.Output.Status = http.StatusOK
		user.Ctx.Output.Body([]byte(`{"result":"delete ` + strconv.Itoa(len(dlist.Userid)) + ` users successfully!"}`))
	}
}

// 读取mongodb， 分页
func (user *UserController) GetUserList() {
	var limit int = 10 //default size
	user.Ctx.Input.Bind(&limit, "limit")
	if limit == 0 {
		limit = 10
	}

	var page int = 1 //default
	user.Ctx.Input.Bind(&page, "page")
	if page == 0 {
		page = 1
	}

	data := utils.SearchUserbyIsDelete(page, limit, 0) // 未删除用户
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body(data)
}

// 读取mongodb， 分页
func (user *UserController) DeletedUserList() {
	var limit int = 10 //default size
	user.Ctx.Input.Bind(&limit, "limit")
	if limit == 0 {
		limit = 10
	}

	var page int = 1 //default
	user.Ctx.Input.Bind(&page, "page")
	if page == 0 {
		page = 1
	}

	data := utils.SearchUserbyIsDelete(page, limit, 1) // 已删除用户
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body(data)
}

// 获取单个用户
func (user *UserController) GetUserById() {
	paramMap := user.Ctx.Input.Params()
	id := paramMap[":id"]

	var result model.User
	var err error

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()
	utable := session.DB("").C(UserTable)

	utable.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&result)
	data, err := json.Marshal(result)
	user.Ctx.Output.Header("Content-Type", "application/json")
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body(data)
	// user.Ctx.Output.ContentType(".json")
}

func (user *UserController) ResetUserPwd() {

	body := user.Ctx.Input.RequestBody
	var reqMap map[string]string
	err := json.Unmarshal(body, &reqMap)

	mobile := reqMap["mobile"]
	pwd := reqMap["password"]

	if mobile == "" || pwd == "" {
		user.Ctx.Output.Status = http.StatusServiceUnavailable
		user.Ctx.Output.Body([]byte("手机号和密码必填"))
		return
	}

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)

	var userInfo model.User

	utable.Find(bson.M{"mobile": mobile, "isdelete": 0}).One(&userInfo)

	id := userInfo.ID

	data := []byte(pwd)
	has := md5.Sum(data)
	passwordmd5 := fmt.Sprintf("%x", has)

	err = utable.Update(
		bson.M{"_id": bson.ObjectId(id)},
		bson.M{"$set": bson.M{"password": passwordmd5}})

	user.HandleError(err)
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body([]byte(`{"result":"update user successfully!"}`))
}

//按id更新用户
func (user *UserController) UpdateUser() {
	paramMap := user.Ctx.Input.Params()
	id := paramMap[":id"]
	if id == "" {
		user.Ctx.Output.Status = http.StatusBadRequest
		user.Ctx.Output.Body([]byte(`{"error":"用户id不能为空"}`))
		// user.HandleError(fmt.Errorf("用户id不能为空"))
	}

	body := user.Ctx.Input.RequestBody
	// bodyJson := user.Ctx.Input.RequestBody
	beego.Info(string(user.Ctx.Input.RequestBody))
	var c model.User
	err := json.Unmarshal(body, &c)

	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)
	beego.Info("ObjectIdHex")
	beego.Info(bson.ObjectIdHex(id))
	err = utable.Update(
		bson.M{"_id": bson.ObjectIdHex(id)},
		bson.M{"$set": bson.M{"name": c.Name,
			"sex":                 c.Sex,
			"nation":              c.Nation,
			"originaddress":       c.OriginAddress,
			"birthaddress":        c.BirthAddress,
			"birthdate":           c.BirthDate,
			"mobile":              c.Mobile,
			"email":               c.Email,
			"professionaltitle":   c.Professionaltitle,
			"education":           c.Education,
			"workexperience":      c.WorkExperience,
			"honor":               c.Honor,
			"company":             c.Company,
			"companyyear":         c.CompanyYear,
			"companynature":       c.CompanyNature,
			"industry":            c.Industry,
			"industrychain":       c.IndustryChain,
			"companycontribution": c.CompanyContribution,
			"advantage":           c.Advantage,
			"requirement":         c.Requirement,
			"supply":              c.Supply,
			"avatar":              c.Avatar,
		}})
	user.HandleError(err)
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body([]byte(`{"result":"update user successfully!"}`))
}

// 上传头像, 需要传入用户ID以存入数据库
func (user *UserController) UploadFile() {
	var id string
	user.Ctx.Input.Bind(&id, "id")

	body := user.Ctx.Input.RequestBody
	var bodyMap map[string]string
	err := json.Unmarshal(body, &bodyMap)
	user.HandleError(err)

	avatar := bodyMap["avatar"]
	if avatar == "" {
		user.HandleError(fmt.Errorf("头像为空"))
	}
	// var Buf bytes.Buffer
	// file, handler, err := user.Ctx.Request.FormFile("uploadfile")
	// if err != nil {
	// 	user.Ctx.Output.Status = http.StatusBadRequest
	// 	user.Ctx.Output.Body([]byte(`{"error":"` + err.Error() + `"}`))
	// }
	// beego.Info(handler.Filename)
	// io.Copy(&Buf, file)

	// save to MongoDB
	session, err := utils.GetMongoSession()
	user.HandleError(err)
	defer session.Close()

	utable := session.DB("").C(UserTable)
	beego.Info(bson.ObjectIdHex(id))
	err = utable.Update(
		bson.M{"_id": bson.ObjectIdHex(id)},
		bson.M{"$set": bson.M{
			"avatar": avatar,
		}})
	user.Ctx.Output.Status = http.StatusOK
	user.Ctx.Output.Body([]byte(`{"result":"upload file successfully!"}`))
}

// func (c *UserController) Get() {

// 	// c.Data["domain"] = ""
// 	c.TplName = "login.html"
// }

// func (c *UserController) Register() {
// 	// c.Data["domain"] = ""
// 	c.TplName = "register.html"
// }

// func (c *UserController) ForgetPassword() {
// 	// c.Data["domain"] = ""
// 	c.TplName = "forgetpassword.html"
// }

// //admin页面更新用户
// func (user *UserController) UpdateUserPage() {
// 	paramMap := user.Ctx.Input.Params()
// 	id := paramMap[":id"]
// 	beego.Info("id++++")
// 	beego.Info(id)
// 	if id == "" {
// 		user.HandleError(fmt.Errorf("用户id不能为空"))
// 	}

// 	var result model.User

// 	var err error

// 	session, err := utils.GetMongoSession()
// 	user.HandleError(err)
// 	defer session.Close()

// 	utable := session.DB("").C(UserTable)

// 	utable.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&result)
// 	beego.Info("result")
// 	beego.Info(result)
// 	data, err := json.Marshal(result)

// 	var dat map[string]interface{}
// 	if err := json.Unmarshal([]byte(data), &dat); err == nil {
// 		user.Data["UserInfo"] = dat
// 	}

// 	user.HandleError(err)
// 	user.TplName = "admin/user_update.html"
// 	// user.Ctx.Output.Body(data)
// }

// 根据id获取用户详情
// func (user *UserController) GetUserInfo() {
// 	// 读取Cookie, 验证用户已登陆, 未登陆返回401
// 	user.IsLoggined()

// 	paramMap := user.Ctx.Input.Params()
// 	id := paramMap[":id"]
// 	beego.Info("id")
// 	beego.Info(string(id))
// 	if id == "" {
// 		user.HandleError(fmt.Errorf("用户id不能为空"))
// 	}

// 	var result model.User

// 	var err error

// 	session, err := utils.GetMongoSession()
// 	user.HandleError(err)
// 	defer session.Close()

// 	utable := session.DB("").C(UserTable)

// 	utable.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&result)
// 	beego.Info("result")
// 	beego.Info(result)
// 	data, err := json.Marshal(result)

// 	var dat map[string]interface{}
// 	if err := json.Unmarshal([]byte(data), &dat); err == nil {
// 		user.Data["UserInfo"] = dat
// 	}
// 	user.Data["EducationAll"] = result.Education
// 	user.Data["WorkAll"] = result.WorkExperience

// 	beego.Info("education")
// 	beego.Info(result.Education)
// 	user.HandleError(err)
// 	user.TplName = "register_info.html"
// 	// user.Ctx.Output.Body(data)
// }

//HandleError 错误处理函数
func (user *UserController) HandleError(err error) {

	if err != nil {
		beego.Error(err.Error())
		user.Ctx.Output.Status = http.StatusServiceUnavailable
		user.Ctx.Output.Body([]byte(err.Error()))
		user.StopRun()
	}
}
